const api = require("../../../../utils/apiUtils");
const utils = require("../../../../utils/utils");
const app = getApp();

Page({
  data: {
    info:{},
    place:{},
    money:'',
    dayMoney:'',
    todayStr:'',
    leaseDate:null,         //日期类型
    revertDateStr:'',
    isAgreement:true,
    formData:{
        leaseStartDate:'',
        leaseDay:1,
        batteryType:null,
        leaseType:2,                    //2:预约到店租借,3:同城快递租借
        appointmentTime:'10:00',
        payType:2,
        appId:my.getAppIdSync().appId
    },
    agreementInfo:{
        title:'用户协议',
        content:'暂无协议内容'
    }
  },
  _buildDate:function(){
    let today = new Date();
    let revertDate = utils.addDay(today,1);
    let formData = this.data.formData;
    formData.leaseStartDate = utils.dateFormat(today);
    this.setData({
        todayStr:utils.dateFormat(today),
        leaseDate:today,
        revertDateStr:utils.dateFormat(revertDate),
        formData:formData
    })
  },

  _loadAgreementInfo:function(type){
      api.post(api.url.agreement,{
          code:type
      },res=>{
          console.log(res)
          if(res.data.code==200){
              this.setData({
                  modalName:'agreement',
                  agreementInfo:res.data.body
              })
          }else if(res.data.msg){
              my.showModal({
                  content: res.data.msg,
                  showCancel:false
              })
          }else{
              my.showToast({
                content: '获取数据失败',
                icon:'error'
              })
          }
      })
  },

  _loadPriceInfo:function(){
      const _self = this;
      api.post(api.url.bxscnBatteryPrice,{
          placeId:this.data.place.placeId,
          batteryType:this.data.formData.batteryType,
          leaseDay:this.data.formData.leaseDay
      },res=>{
          console.log(res)
          if(res.data.code==200){
              let info = _self.data.info;
              info.depositMoney = res.data.body.depositMoney;
              _self.setData({
                  dayMoney:res.data.body.dayMoney,
                  money:res.data.body.money,
                  info:info
              })
          }else if(res.data.msg){
              my.showModal({
                  content: res.data.msg,
                  showCancel:false
              })
          }else{
              my.showToast({
                content: '计算费用失败',
                icon:'error'
              })
          }
      })
  },

  bindHideModal:function(){
      this.setData({
          modalName:null
      })
  },

  btnChangeAgreement(){
      this.setData({
          isAgreement:!this.data.isAgreement
      })
  },

  btnPickerChange:function(e){
      let key = e.currentTarget.dataset.key;
      let formData = this.data.formData;
      if('leaseStartDate' == key){
          let date = new Date(e.detail.value);
          //计算与今天的间隔，不能超过5天
          let day = utils.diffDay(new Date(),date);
          if(day > 5){
              my.showModal({
                title: '温馨提示',
                content: '起租日请选择距离今天五天以内',
                showCancel:false
              })
              return;
          }

          console.log(date);
          formData.leaseStartDate = utils.dateFormat(date);
          let revertDate = utils.addDay(date,formData.leaseDay);
          this.setData({
              leaseDate:date,
              revertDateStr:utils.dateFormat(revertDate),
              formData:formData
          })
      }else if('revertDate' == key){
          let date = new Date(e.detail.value);
          let leaseDay = utils.diffDay(this.data.leaseDate,date);
          console.log("租借时长：" + leaseDay);
          if(leaseDay <= 0){
              formData.leaseDay = 1;
              this.setData({
                  revertDateStr:formData.leaseStartDate,
                  formData:formData
              })
              this._loadPriceInfo();
          }else if(leaseDay > 50){
              my.showModal({
                  title: '温馨提示',
                  content: '租借天数不能超过50天',
                  showCancel:false
              })
              return;
          }else{
              formData.leaseDay = leaseDay;
              this.setData({
                  revertDateStr:utils.dateFormat(date),
                  formData:formData
              })
              this._loadPriceInfo();
          }
      }else if('appointmentTime' == key){
          formData.appointmentTime =  e.detail.value;
          this.setData({
              formData:formData
          })
      }
  },

  btnAgreementInfo:function(e){
      let key = e.currentTarget.dataset.key;
      if('RentAgreement' == key){
          //租凭服务协议
          this._loadAgreementInfo(key);
      }else if('PrivacyAgreement' == key){
          //隐私协议
          this._loadAgreementInfo(key);
      }
  },

  btnPriceList:function(e){
      this.setData({
          modalName:'priceList'
      })
  },

  btnPay:function(e){
      if(!this.data.isAgreement){
          my.showModal({
              title: '温馨提示',
              content: '请阅读并同意《租凭服务协议》和《隐私协议》',
              showCancel:false
          })
          return;
      }
      
      let formData = this.data.formData;
      if(formData.leaseDay == 0){
          my.showToast({content:'请选择租借时长',icon:'none'})
          return;
      }
      if(formData.leaseType == 3){
          if(addressInfo.id){
              buyData.addressId = addressInfo.id
          }else{
              my.showToast({content:'请选择收货地址',icon:'none'})
              return;
          }
      }
      my.showLoading({title: '支付中...'})
      api.post(api.url.bxscnBatteryPay,formData,res=>{
          if(res.data.code==200){
              const tradeNo = res.data.body.tradeNo;
              let count = 0;
              let timer = setInterval(()=>{
                  count++;
                  if(count>30){
                      clearInterval(timer);
                      timer = null;
                      my.hideLoading();
                  }
                  api.post(api.url.bxscnBatteryPayResult,{
                      tradeNo:tradeNo,
                      payType:3
                  },res=>{
                      if(res.data.code == 200){
                          if(res.data.body.resultCode==2){
                              clearInterval(timer);
                              my.hideLoading();
                              my.showToast({
                                  content: '支付成功！',
                                  icon:'success',
                                  mask:true,
                                  success:()=>{
                                      setTimeout(() => {
                                          my.reLaunch({url: `/pages/order/bxscn/shop/info?tradeNo=${tradeNo}`});
                                      }, 1000);
                                  }
                              })
                          }
                      }
                  })
              },1000)

              my.tradePay ({
                tradeNO: tradeNo,
                success: res => {
                  if(!timer){
                    my.showToast({
                        content: '支付成功！',
                        icon:'success',
                        mask:true,
                        success:()=>{
                            setTimeout(() => {
                              my.reLaunch({url: `/pages/order/bxscn/shop/info?tradeNo=${tradeNo}`});
                            }, 1000);
                        }
                    })
                  }
                },
                fail: error => {
                  my.hideLoading();
                  clearInterval(timer);
                  timer = null;
                  my.showToast({
                    content: '支付失败',
                    icon:'error',
                    mask:true
                  })
                },
              });
          }else if(res.data.msg){
              my.hideLoading();
              my.showModal({
                  content:res.data.msg,
                  showCancel:false
              })
          }else{
              my.hideLoading();
              my.showToast({
                content:'预约失败',
                icon:'error',
                mask:true
              })
          }
      })
  },
  onLoad() {
    const _self = this;
    const eventChannel = this.getOpenerEventChannel();
    try{
        eventChannel.on('fromData', function(data) {
            console.log(data);
            let formData = _self.data.formData;
            let money = Number.parseFloat(data.info.depositMoney) + Number.parseFloat(data.info.dayMoney);
            formData.batteryType = data.info.id;
            formData.placeId = data.place.placeId;
            _self.setData({
                info:Object.assign({},data.info),      //拷贝，避免该页面修改影响列表页面数据变更
                place:Object.assign({},data.place),
                formData:formData,
                dayMoney:data.info.dayMoney,
                money:money
            })
            _self._buildDate();
            _self._loadPriceInfo();
        })
    }catch (e) {
        console.error(e);
        my.showToast({
          content: '参数错误',
          icon:'error'
        })
       // setTimeout(() => {
        //    my.navigateBack();
        //}, 1000);
    }
  },
});
